<template>
	<view class="contain">
		<u-navbar backIconName="" :back-text="lang.index.bluetooth">
			<view class="navRight" slot="right"><u-switch v-model="checked" :size="size" @change="toggle" active-color="#39e55c" inactive-color="#eee"></u-switch></view>
		</u-navbar>
		<view class="list">
			<view class="list-title">{{ lang.index.equipment }}</view>
			<view class="list-item" v-for="(v, k) in blueList" :key="k" @tap="goConnect(v)" hover-class="hover-gray">{{ v.name ? v.name : v.deviceId }}</view>
		</view>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import Toast from '../../common/toast.js';
export default {
	data() {
		return {
			checked: false,
			size: 50,
			deviceId: null,
			serviceId: null,
			characteristicId: null,
			state: false,
			blueList: [],
			historyBadsList: []
		};
	},
	computed: {
		...mapState(['lang', 'connectState'])
	},
	onLoad() {
		for (let i = 0; i <= 3; i++) {
			let text = i == 0 ? this.lang.tabBar.bluetooth : i == 1 ? this.lang.tabBar.work : i == 2 ? this.lang.tabBar.setting : this.lang.tabBar.me;
			uni.setTabBarItem({
				index: i,
				text
			});
		}
		if (uni.getStorageSync('bads')) {
			this.historyBadsList = JSON.parse(uni.getStorageSync('bads'));
		}
	},
	methods: {
		toggle(status) {
			console.log(status);
			// this.$util.throttle(()=>{
			if (status) {
				this.openBluetooth();
			} else {
				this.$store.commit('setConnectState', false);
				this.closeBlueAdapter();
			}
			// })
		},
		findNewBluetooth(devices) {
			let devicesItem = devices[0];
			if (devicesItem.name.indexOf('ENBLE') != -1 || devicesItem.name.indexOf('RF-STAR-SMMT') != -1) {
				let array = this.historyBadsList.filter(e => e.deviceId == devicesItem.deviceId);
				if (array.length != 0) {
					this.blueList.unshift(devicesItem);
				} else {
					this.blueList.push(devicesItem);
				}
			}
		},
		errMessage(errorCode) {
			if (errorCode == 10000) return this.lang.link.noInit;
			if (errorCode == 10001) return this.lang.link.notavailable;
			if (errorCode == 10002) return this.lang.link.nodevice;
			if (errorCode == 10003) return this.lang.link.connectionfail;
			if (errorCode == 10004) return this.lang.link.noservice;
			if (errorCode == 10005) return this.lang.link.nocharacteristic;
			if (errorCode == 10006) return this.lang.link.noconnection;
			if (errorCode == 10007) return this.lang.link.propertynotsupport;
			if (errorCode == 10008) return this.lang.link.systemerror;
			if (errorCode == 10009) return this.lang.link.systemnotsupport;
			return this.lang.link.unknown;
		},
		getBluetoothAdapterState() {
			let _this = this;
			uni.getBluetoothAdapterState({
				success(res) {
					console.log(res);
					Toast.showToast(_this.lang.index.InitBluetooth);
					uni.startBluetoothDevicesDiscovery({
						services: ['6E400001-B5A3-F393-E0A9-E50E24DCCA9E'],
						allowDuplicatesKey: false,
						success(result) {
							console.log(result);
						},
						fail: err => {
							Toast.showToast(_this.errMessage(err.code))
						}
					});
				},
				fail: err => {
					Toast.showToast(_this.errMessage(err.code))
				}
			});
		},
		// 开始搜索蓝牙
		openBluetooth() {
			var self = this;
			uni.openBluetoothAdapter({
				success: res => {
					self.getBluetoothAdapterState();
				},
				fail: err => {
					console.log('初始化蓝牙失败:' + err.code);
					Toast.showToast(self.errMessage(err.code))
				}
			}),
				// onBluetoothDeviceFound
				/* 搜索蓝牙设备回调 */
				uni.onBluetoothDeviceFound(CALLBACK => {
					/* 搜索过程中如果搜索到需要的设备 */
					console.log('蓝牙搜索结果' + JSON.stringify(CALLBACK));
					self.findNewBluetooth(CALLBACK.devices);
				}),
				/* 监听蓝牙适配器状态变化事件  可以检测当前设备的蓝牙的断开或者连接的情况*/
				uni.onBluetoothAdapterStateChange(function(CALLBACK) {
					//CALLBACK.available 蓝牙适配器是否可用
					//CALLBACK.discovering 蓝牙适配器是否处于搜索状态
					console.log('适配器状态变化', CALLBACK);
				});
		},
		closeBlueAdapter() {
			let _this = this;
			uni.closeBluetoothAdapter({
				success() {
					console.log(1111);
					//Toast.showToast("关闭蓝牙适配器成功");
					Toast.showToast(_this.lang.index.OffBluetooth);
					_this.blueList = [];
					// this.$forceUpdate();
				}
			});
		},
		goConnect(item) {
			this.$util.throttle(() => {
				let array = this.historyBadsList;
				if (array.length == 0) {
					array.push(item);
				} else {
					array.forEach(e => {
						if (e.deviceId != item.deviceId) {
							array.unshift(item);
						}
					});
				}
				this.$store.commit('setConnectState', true);
				this.$store.commit('setDeviceId', item.deviceId);
				uni.setStorageSync('bads', JSON.stringify(array));
				Toast.showToast(this.lang.index.bluetoothconnectsucc);
				uni.stopBluetoothDevicesDiscovery();
				uni.switchTab({
					url: '/pages/set/set'
				});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.navRight {
	padding-right: 24rpx;
}
.contain {
	width: 100%;
	background: #fbfbfb;
	display: flex;
	flex-direction: column;
	align-items: center;

	.title {
		width: 100%;
		padding: 80rpx 28rpx 30rpx;
		box-sizing: border-box;
		background: #ffffff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 30rpx;
		font-weight: 500;
	}
	.list {
		width: 100%;
		padding: 0 28rpx;
		box-sizing: border-box;
		background: #f1f1f1;

		.list-title {
			width: 100%;
			padding: 28rpx 24rpx;
			box-sizing: border-box;
			font-size: 28rpx;
			color: #333;
		}

		.list-item {
			width: 100%;
			padding: 30rpx 24rpx;
			box-sizing: border-box;
			background: #ffffff;
			border-radius: 6px;
			font-size: 28rpx;
			color: #333;
			margin-bottom: 30rpx;
		}
	}
}
</style>
